﻿namespace LiteBlog.Common.Components
{
    using log4net;
    using log4net.Appender;
    using log4net.Config;
    using log4net.Core;
    using log4net.Layout;
    using log4net.Repository.Hierarchy;
    using System;
    using System.Globalization;
    using System.IO;
    using System.Web;


    public static class Logger
    {
        private static object lockObj = new object();
        private static ILog logger = LogManager.GetLogger("root");

        public static void Init(string logFile, string logLevel)
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository();
            var appender = new RollingFileAppender();
            appender.File = logFile;
            appender.LockingModel = new FileAppender.MinimalLock();
            appender.RollingStyle = RollingFileAppender.RollingMode.Size;
            appender.MaxSizeRollBackups = 10;
            appender.MaxFileSize = 100000;
            appender.ImmediateFlush = true;
            appender.AppendToFile = true;
            var patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%d{dd MMM yyyy HH:mm:ss} %-5p - %m%n";
            appender.Layout = patternLayout;
            patternLayout.ActivateOptions();
            appender.ActivateOptions();
            hierarchy.Root.AddAppender(appender);
            hierarchy.Root.Level = hierarchy.LevelMap[logLevel] ?? Level.All;
            hierarchy.Configured = true;
            BasicConfigurator.Configure(hierarchy);
        }

        

        public static void Log(string message)
        {
            Log(message, null);
        }

        public static void Info(string message)
        {
            if (logger.IsInfoEnabled)
                logger.Info(message);
        }

        public static void Warn(string message)
        {
            if (logger.IsWarnEnabled)
                logger.Warn(message);
        }

        public static void Error(string message)
        {
            if (logger.IsErrorEnabled)
                logger.Error(message);
        }

        public static void Debug(string message)
        {
            if (logger.IsDebugEnabled)
                logger.Debug(message);
        }

        public static void Fatal(string message)
        {
            if (logger.IsFatalEnabled)
                logger.Fatal(message);
        }

        public static void Log(string message, Exception ex)
        {
            if (logger.IsErrorEnabled)
                logger.Error(message, ex);
        }


    }
}